import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:hitutor/UI/HiNote/TeachMaterial/TeachMaterialManager.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/Check.dart';
import 'package:hitutor/Widget/ChooserBox.dart';
import 'package:hitutor/Widget/MyBgPage.dart';
import 'package:hitutor/Widget/MyButton.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:image_picker/image_picker.dart';

class UploadTM extends StatefulWidget {
  XFile file;

  UploadTM(this.file);

  @override
  State<StatefulWidget> createState() {
    return _UploadTM();
  }
}

class _UploadTM extends State<UploadTM> {
  List<XFile> xfiles = [];
  final ImagePicker _picker = ImagePicker();

  dynamic selectedRoom;
  static int BindRoom = 0;

  static int BindClass = 1;
  dynamic selectedClass;

  int bind = BindRoom;

  @override
  void initState() {
    xfiles.add(widget.file);
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      getRoomAndClass();
    });
    super.initState();
  }

  getRoomAndClass() {
    HttpGo(context).get("/Lesson/GetBindingClassroomAndOrderList?studentId=${Global.studentId}", {}, (data) {
      rooms = data["classroomList"];
      clazzs = data["purchaseOrderList"];
      setState(() {});
    }, (code, error) => showToast(error));
  }

  openAlbum() async {
    final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
    if (image != null) xfiles.add(image);
    setState(() {});
  }

  openCamera() async {
    final XFile? image = await _picker.pickImage(source: ImageSource.camera);
    if (image != null) xfiles.add(image);
    setState(() {});
  }

  List<dynamic> rooms = [];

  chooseRoom() {
    showWheelDialog2(context, "", rooms, "displayClassroom", (i) {
      selectedRoom = rooms[i];
      setState(() {});
    });
  }

  List<dynamic> clazzs = [];

  chooseClass() {
    showWheelDialog2(context, "", clazzs, "displayLessonName", (i) {
      selectedClass = clazzs[i];
      setState(() {});
    });
  }

  confirmClick() async {
    List<MultipartFile> files = [];
    for (var item in xfiles) {
      MultipartFile file = await MultipartFile.fromFile(item.path);
      files.add(file);
    }
    Map<String, dynamic> params = {};
    if (bind == BindClass) {
      if (selectedClass == null) {
        showToast("請選擇課程");
        return;
      }

      params["id"] = selectedClass["purchaseOrderId"];
      params["idType"] = "purchaseOrder";
    } else if (bind == BindRoom) {
      if (selectedRoom == null) {
        showToast("請選擇教室");
        return;
      }
      params["id"] = selectedRoom["classroomId"];
      params["idType"] = "classroom";
    }
    params["files"] = files;
    HttpGo(context, json: false).post("/Material/BindingOwnMaterialFiles", params, (data) {
      PageUtil().openReplace(context, TeachMaterialManager());
    }, (code, error) => showToast(error));
  }

  @override
  Widget build(BuildContext context) {
    return MyBgPage(
        "",
        Container(
            margin: EdgeInsets.fromLTRB(16, 16, 16, 24),
            decoration: Global.getWhiteBg_shadow(8, MyColor.DD),
            child: SingleChildScrollView(
              padding: EdgeInsets.fromLTRB(16, 16, 16, 16),
              child: Column(children: [
                Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                  LocalImage("save_icon.png", height: 24, width: 32),
                  Text("Save Files", style: TextStyle(fontSize: 15, color: MyColor.Orange, fontWeight: FontWeight.bold))
                ]),
                Container(height: 0.5, color: MyColor.Orange, margin: EdgeInsets.only(top: 6, bottom: 16)),
                Container(
                    decoration: Global.getBg(Color(0xfff4f5f5), 8),
                    margin: EdgeInsets.only(bottom: 16),
                    child: ListView.builder(
                        itemCount: xfiles.length,
                        shrinkWrap: true,
                        physics: NeverScrollableScrollPhysics(),
                        padding: EdgeInsets.all(8),
                        itemBuilder: (BuildContext context, int index) {
                          return Container(
                              padding: EdgeInsets.all(4),
                              child: Row(children: [
                                LocalImage("picture.png", width: 28, height: 18),
                                Expanded(child: Text("${xfiles[index].name}", style: TextStyle(fontSize: 15, color: MyColor.C7D)))
                              ]));
                        })),
                Row(children: [
                  Expanded(child: Button("從相簿中選擇", bgColor: MyColor.Orange, height: 34, onTap: openAlbum)),
                  Container(width: 16),
                  Expanded(child: Button("從相機上傳", bgColor: MyColor.Orange, height: 34, onTap: openCamera))
                ]),
                Container(height: 16),
                Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                  GestureDetector(
                      child: Check(bind == BindRoom),
                      onTap: () {
                        bind = BindRoom;
                        setState(() {});
                      }),
                  Text(" 綁定教室", style: TextStyle(fontSize: 16, color: bind == BindRoom ? MyColor.Green : MyColor.C7D))
                ]),
                Visibility(
                    visible: bind == BindRoom,
                    maintainState: true,
                    maintainSize: true,
                    maintainAnimation: true,
                    child: ChooserBox(selectedRoom == null ? "" : selectedRoom["displayClassroom"],
                        hintText: "選擇教室", margin: EdgeInsets.only(top: 16, bottom: 16), onTap: chooseRoom)),
                Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                  GestureDetector(
                      child: Check(bind == BindClass),
                      onTap: () {
                        bind = BindClass;
                        setState(() {});
                      }),
                  Text(" 綁定課程", style: TextStyle(fontSize: 16, color: bind == BindClass ? MyColor.Green : MyColor.C7D))
                ]),
                Visibility(
                    visible: bind == BindClass,
                    maintainState: true,
                    maintainSize: true,
                    maintainAnimation: true,
                    child: ChooserBox(selectedClass == null ? "" : selectedClass["displayLessonName"],
                        hintText: "選擇課程", margin: EdgeInsets.only(top: 16, bottom: 16), onTap: chooseClass)),
                Button("確 定", bgColor: MyColor.Green, width: 84, margin: EdgeInsets.only(top: 16), onTap: confirmClick)
              ]),
            )));
  }
}
